package com.example.prodclass.controller;

import com.example.category.pojo.Category;
import com.example.category.service.CategoryService;
import com.example.goods.pojo.Goods;
import com.example.goods.service.GoodsService;
import com.example.pcc.pojo.Pcc;
import com.example.pcc.service.PccService;
import com.example.prodclass.pojo.PccVo;
import com.example.prodclass.service.ProdclassService;
import com.example.prodclass.pojo.Prodclass;
import com.example.prodclass.pojo.ProductVo;
import com.example.smartcommon.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/prodclass/")
@Tag(name = "显示商品分类")
public class ProdclassController {
    @Autowired
    private ProdclassService prodclassService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private PccService pccService;
    @Autowired
    private CategoryService categoryService;

    @Operation(summary = "获得所有的商品分类")
    @GetMapping(value = "/getAllProdclass")
    public R getAllProdclass() {
        List< ProductVo > res = new ArrayList<>();
        List< Prodclass > prodclassList = prodclassService.list();

        // 获取商品ID集合
        Set< Integer > goodsIdSet = prodclassList.stream()
                .flatMap(item -> Arrays.stream(item.getProdclassGoods().split(",")).map(Integer::valueOf))
                .collect(Collectors.toSet());

        // 获取商品信息
        List< Goods > goodsList = goodsService.listByIds(new ArrayList<>(goodsIdSet));
        Map< Integer, Goods > goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getGoodsId, Function.identity()));

        // 获取所有 ProdclassChildren ID
        Set< Integer > pccIds = prodclassList.stream()
                .map(Prodclass::getProdclassChildren)
                .collect(Collectors.toSet());

        // 批量查询 Pcc
        Map< Integer, Pcc > pccMap = pccService.listByIds(new ArrayList<>(pccIds))
                .stream()
                .collect(Collectors.toMap(Pcc::getPccId, Function.identity()));

        // 使用Stream进行分组和合并
        Map< Integer, List< Prodclass > > groupedProdclassList = prodclassList.stream()
                .collect(Collectors.groupingBy(Prodclass::getCategoryId));

        // 遍历分组后的数据
        groupedProdclassList.forEach((categoryId, prodclassGroup) -> {
            // 进行合并处理
            List< Goods > goodsLists = prodclassGroup.stream()
                    .flatMap(item -> Arrays.stream(item.getProdclassGoods().split(",")).map(Integer::valueOf))
                    .map(goodsMap::get)
                    .collect(Collectors.toList());

            Collections.shuffle(goodsLists, new Random());

            // 构建 ProductVo
            Category category = categoryService.getById(categoryId);
            ProductVo productVo = new ProductVo();
            BeanUtils.copyProperties(prodclassGroup.get(0), productVo);
            productVo.setCategoryId(category.getCategoryId());
            productVo.setCategoryName(category.getCategoryName());
            productVo.setCategoryIcon(category.getCategoryIcon());

            // 构建 PccVo 列表
            List< PccVo > pccList = prodclassGroup.stream()
                    .map(item -> {
                        int pccId = item.getProdclassChildren();
                        PccVo pccVo = new PccVo();
                        Pcc pcc = pccMap.get(pccId);
                        pccVo.setPccId(pccId);
                        pccVo.setPccName(pcc.getPccName());
                        pccVo.setPccPicture(pcc.getPccPicture());
                        pccVo.setPccParent(null);
                        // 使用原始的 prodChildren 数据
                        pccVo.setGoodsList(goodsLists.stream()
                                .filter(goods -> Arrays.stream(item.getProdclassGoods().split(","))
                                        .map(Integer::valueOf).toList().contains(goods.getGoodsId()))
                                .collect(Collectors.toList()));
                        return pccVo;
                    })
                    .collect(Collectors.toList());

            // 设置 PccVo 列表到 ProductVo
            productVo.setProdChildren(pccList);
            res.add(productVo);
        });

        return R.ok("查询所有商品分类成功").data("prodclassList", res);
    }

    @Operation(summary = "增加商品分类")
    @PostMapping(value = "/addProdclass")
    public R addProdclass(@RequestBody Prodclass prodclass) {
        boolean flag = prodclassService.save(prodclass);
        if (flag) {
            return R.ok("增加商品分类成功");
        } else {
            return R.error("增加商品分类失败");
        }
    }

    @Operation(summary = "删除商品分类数据")
    @DeleteMapping(value = "/deleteProdclass/{id}")
    public R deleteProdclass(@PathVariable("id") Integer bannerId) {
        boolean flag = prodclassService.removeById(bannerId);
        if (flag) {
            return R.ok("删除商品分类成功");
        } else {
            return R.error("删除商品分类失败");
        }
    }

    @Operation(summary = "按照商品分类编号查询数据")
    @GetMapping(value = "/getProdclassById/{id}")
    public R getByIdProdclass(@PathVariable("id") Integer bannerId) {
        Prodclass prodclass = prodclassService.getById(bannerId);
        return R.ok("按照商品分类编号查询数据成功").data("banner", prodclass);
    }

    @Operation(summary = "修改商品分类数据")
    @PutMapping(value = "/updateProdclass")
    public R updateProdclass(@RequestBody Prodclass prodclass) {
        boolean flag = prodclassService.updateById(prodclass);
        if (flag) {
            return R.ok("修改商品分类成功");
        } else {
            return R.error("修改商品分类失败");
        }
    }
}
